﻿namespace PugLib.Extensions.Collections
{
	using System.Collections.Generic;
	using System.Collections.ObjectModel;
	using System.Linq;

	public static class ReadOnlyCollectionExtensions
	{
		// Methods
		public static ReadOnlyCollection<T> ToReadOnlyCollection<T>(this IEnumerable<T> sequence)
		{
			if (sequence == null)
			{
				return DefaultReadOnlyCollection<T>.Empty;
			}
			ReadOnlyCollection<T> onlys = sequence as ReadOnlyCollection<T>;
			return onlys ?? new ReadOnlyCollection<T>(sequence.ToArray());
		}

		// Nested Types

		#region Nested type: DefaultReadOnlyCollection

		private static class DefaultReadOnlyCollection<T>
		{
			// Fields
			private static ReadOnlyCollection<T> _defaultCollection;

			// Properties
			internal static ReadOnlyCollection<T> Empty
			{
				get
				{
					if (_defaultCollection == null)
					{
						_defaultCollection = new ReadOnlyCollection<T>(new T[0]);
					}
					return _defaultCollection;
				}
			}
		}

		#endregion
	}
}